import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { AuthService } from '../service/auth.service';
import { TokenStorageService } from '../service/storage.service';

@Component({
  selector: 'app-auth',
  templateUrl: './auth.component.html',
  styleUrls: ['./auth.component.scss']
})
export class AuthComponent implements OnInit {
  public login = {
    username: '',
    pwd: '',
    confirmPwd: ''
  }

  constructor(public authService: AuthService, public storageService: TokenStorageService) { 
  }
  ngOnInit() { 
  }

  async doLogin() { 
    if (!this.login.username) {
      return alert("缺少用户名");
    }
    if (!this.login.pwd) {
      return alert("缺少密码");
    }
    try {
      let token = await this.authService.login(this.login.username, this.login.pwd);
      if (!token) {
        return alert('用户名或密码错误');
      }
      alert('登录成功');
      this.storageService.setToken(token);
      window.location.reload();
    } catch (err) { 
      console.error(err);
      alert("用户名或密码错误");
    }
  }

  async doRegistry() { 
    if (!this.login.username) { 
      return alert("缺少用户名");
    }
    if (!this.login.pwd) { 
      return alert("缺少密码");
    }
    if (this.login.pwd != this.login.confirmPwd) { 
      return alert('两次密码不一致');
    }
    let ret = await this.authService.registry(this.login.username, this.login.pwd);
    alert('注册成功,您现在可以登录了!');
    window.location.reload();
  }
}
